package cn.iocoder.yudao.module.system.controller.admin.mini.other.shopGuide.util;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.back.controller.admin.back.WxLoginVo;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.file.vo.MultipartFileToFile;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.file.vo.OssUtil;
import net.sf.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取小程序二维码
 */
public class ShopQrCodeUtil {

    public static String getAccessToken() throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WxLoginVo.appid + "&secret=" + WxLoginVo.secret;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = client.newCall(request).execute();
        String responseData = response.body().string();

        JSONObject jsonObject = JSONObject.fromObject(responseData);
        return jsonObject.getString("access_token");
    }


    public static ByteArrayInputStream sendPost(String URL, String json) {
        InputStream inputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(URL);
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 获取相应实体
                HttpEntity entity = response.getEntity();
                inputStream = entity.getContent();
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                // 创建一个Buffer字符串
                byte[] buffer = new byte[1024];
                // 每次读取的字符串长度，如果为-1，代表全部读取完毕
                int len = 0;
                // 使用一个输入流从buffer里把数据读取出来
                while ((len = inputStream.read(buffer)) != -1) {
                    // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                    outStream.write(buffer, 0, len);
                }
                // 关闭输入流
                inputStream.close();
                // 把outStream里的数据写入内存
                byteArrayInputStream = new ByteArrayInputStream(outStream.toByteArray());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArrayInputStream;
    }

    /**
     * 获取小程序菊花码
     *parm：machineNo    二维码想携带的参数
     **/
    public static String getWXCode(String machineNo) throws IOException {
        String access_token=getAccessToken();
        String aiyunUrl = "";
        try {

            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
            Map<String, String> param = new HashMap<>();
            //scene参数
            param.put("scene", machineNo);
            //这里的page如果没有的话可以不写，默认是跳主页，如果写了没有的页面的话，会返回错误信息
//            param.put("page", "pages/index/index");
            String json = com.alibaba.fastjson.JSON.toJSONString(param);
            ByteArrayInputStream inputStream = sendPost(url, json);

            ByteArrayOutputStream byteArrayOutputStream = null;
            byteArrayOutputStream = new ByteArrayOutputStream();
            int i;
            byte[] buffer = new byte[200];
            while ((i = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, i);
            }
            byteArrayOutputStream.close();

            FileOutputStream fileOutputStream = new FileOutputStream("barcode.png");
            byteArrayOutputStream.writeTo(fileOutputStream);

            File outputFile = new File("barcode.png");
            aiyunUrl = OssUtil.uploadFileToOss(outputFile);

            MultipartFileToFile.deleteTempFile(outputFile);
            outputFile.delete();

        } catch (Exception e) {
            throw new ServiceException(500,e.getMessage());
        }
        return aiyunUrl;
    }
    public static void main(String[] args) throws IOException {
        System.err.println(getWXCode("11"));
    }
}
